package com.sy.common.service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sy.cloud.guess.model.*;
import com.sy.cloud.wechat.model.WechatUser;
import com.sy.cloud.wechat.model.Wxuser;
import com.sy.common.model.Juejinuser;
import com.sy.common.persistence.QueryHelper;
import com.sy.common.util.DatabaseContextHolder;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by mac on 2017/12/6.
 */
@Transactional
@Service
@Slf4j
public class TestService implements ITestService {
    @Resource
    private IBaseService baseService;

    @Override
    public Juejinuser getJueUserById(String id) {
        StringBuilder sb = new StringBuilder();
        sb.append("From Juejinuser where id = ");
        sb.append(id);
        Juejinuser juejinuser = baseService.queryObjectFromMaster(sb.toString(), Juejinuser.class);
        if (juejinuser != null) {
            return juejinuser;
        }
        return null;
    }

    @Override
    public Juejinuser getJueUserByPhone(String phone) {
        StringBuilder sb = new StringBuilder();
        sb.append("From Juejinuser where phone = '");
        sb.append(phone);
        sb.append("'");
        Juejinuser juejinuser = baseService.queryObjectFromMaster(sb.toString(), Juejinuser.class);
        if (juejinuser != null) {
            return juejinuser;
        }
        return null;
    }

    @Override
    public void addUser(Juejinuser juejinuser) {
        baseService.update(juejinuser);
    }

    @Override
    public void addPayOrder(PayOrder order) {
        baseService.update(order);
    }

    @Override
    public void addModel(WechatUser wechatUser) {
        baseService.update(wechatUser);
    }

    @Override
    public WechatUser getWechatInfo(String openid) {

        StringBuilder hql = new StringBuilder();
        hql.append("From WechatUser where open_id = '");
        hql.append(openid);
        hql.append("'");

        WechatUser wechatUser = baseService.queryObjectFromMaster(hql.toString(), WechatUser.class);
        return wechatUser;
    }

    /**
     * 通过
     *
     * @param openId
     */
    @Override
    public void getwxuser(String openId) {

    }

    @Override
    public void updateUser(Juejinuser juejinuser) {
        baseService.update(juejinuser);
    }


    @Override
    public Double getMoney(String phone) {
        if( phone == null ){
            log.info("phone为空");
            return 0.0;
        }
        StringBuilder selectSql0 = new StringBuilder();
        selectSql0.append(" From Juejinuser u where phone = '");
        selectSql0.append(phone);
        selectSql0.append("'");
        List<Juejinuser> list = baseService.listQuery(selectSql0.toString(), Juejinuser.class);


        if (list.size() > 0) {
            Juejinuser juejinuser = list.get(0);
            return juejinuser.getCoin();
        }
        return 0.0;

    }

    /**
     * 下单接口
     *
     * @param orderlist
     * @return
     */
    @Override
    public boolean dealdb(List<JOrder> orderlist) {
        try {
            baseService.batchCreate(orderlist);

            // 往buffer里面更新记录
//            List<Orderbuffer> orderbuffers = baseService.listQuery("From Orderbuffer", Orderbuffer.class);
//            Orderbuffer orderbuffer = orderbuffers.get(0);
//            for( int i = 0;i< orderlist.size();i++ )
//            {
//                JOrder order = orderlist.get(i);
//                switch ( order.getCapital() ){
//                    case 10:
//                        orderbuffer.setT0(  orderbuffer.getT0() + order.getAmount() );
//                        break;
//                    case 11:
//                        orderbuffer.setT1(  orderbuffer.getT1() + order.getAmount() );
//                        break;
//                    case 12:
//                        orderbuffer.setT2(  orderbuffer.getT2() + order.getAmount() );
//                        break;
//                    case 13:
//                        orderbuffer.setT3(  orderbuffer.getT3() + order.getAmount() );
//                        break;
//                    case 14:
//                        orderbuffer.setT4(  orderbuffer.getT4() + order.getAmount() );
//                        break;
//                    case 15:
//                        orderbuffer.setT5(  orderbuffer.getT5() + order.getAmount() );
//                        break;
//                }
//                baseService.update( orderbuffer );
//            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 把计算出来的中奖结果存到表中
     *
     * @param gok
     * @return
     */
    @Override
    public boolean updateGokguessnum(Gokguessnum gok) {
        // 添加中奖结果
        long l1 = System.currentTimeMillis() / 1000;
        gok.setCreate_time(l1 + "");

        baseService.create(gok);
        // 更新订单缓存中的记录，清0
//        List<Orderbuffer> orderbuffers = baseService.listQuery("From Orderbuffer", Orderbuffer.class );
//        Orderbuffer orderbuffer = orderbuffers.get(0);
//        // 更新订单缓存中的金额，清0
//        orderbuffer.setT0(0);
//        orderbuffer.setT1(0);
//        orderbuffer.setT2(0);
//        orderbuffer.setT3(0);
//        orderbuffer.setT4(0);
//        orderbuffer.setT5(0);
//        baseService.update( orderbuffer );

        // 更新订单表里的记录
        updateWinaOrLose(gok.getIssue(), gok);
        return true;
    }

    /**
     * 获得当前数据库里的最大的issue
     *
     * @return
     */
    @Override
    public String getMaxIssue() {
        String hql = "select max(issue) as adf from sp_gokguess_num";
        List<Object[]> objectslist = new ArrayList<>();
        String id = "";
        try {
            objectslist = baseService.nativeQuery(hql);
            if (objectslist.size() > 0) {
                Object object = objectslist.get(0);
                id = object.toString();
            }
        } catch (Exception e) {

        }
        return id;
    }

    @Override
    public String getNowIssue() {
        String issue = getMaxIssue();
        SimpleDateFormat df = new SimpleDateFormat("MMdd");//设置日期格式
        String s1 = df.format(new Date());
        String s4 = "";

        if (issue.length() == 8) {
            String s2 = issue.substring(4, 8);
            Integer i3 = Integer.parseInt(s2) + 1;
            s4 = s1 + String.format("%04d", i3); // 生成新的issue
        } else if (issue.length() == 7) {
            String s2 = issue.substring(3, 7);
            Integer i3 = Integer.parseInt(s2) + 1;
            s4 = s1 + String.format("%04d", i3); // 生成新的issue
        } else {
            s4 = s1 + "0001";
        }
        return s4;
    }

    /**
     * 更新订单列表中的所有未结算订单
     */
    @Override
    public void updateWinaOrLose(Integer issue, Gokguessnum gok) {
        long ter = System.currentTimeMillis();
        long ter1 = ter / 1000;
        int i0 = (int) ter1;
        int i1 = (int) System.currentTimeMillis() / 1000 - 100;
        i1 = i0 - 100;
        StringBuilder hql = new StringBuilder();
        hql.append("From JOrder where issue is null");
        log.info(hql.toString());
        List<JOrder> orders = baseService.listQuery(hql.toString(), JOrder.class);


        for (int i = 0; i < orders.size(); i++) {
            JOrder order = orders.get(i);
            order.setIs_win(0);
            // 判断精确场
            switch (order.getCapital()) {
                case 10:
                    // 客户买单
                    if (gok.isSingle()) {
                        order.setIs_win(1);
                    }
                    break;
                case 11:
                    // 客户买双
                    if (gok.isIfdouble()) {
                        order.setIs_win(1);
                    }
                    break;
                case 12:
                    // 客户买大
                    if (gok.isBig()) {
                        order.setIs_win(1);
                    }
                    break;
                case 13:
                    // 客户买小
                    if (gok.isLittle()) {
                        order.setIs_win(1);
                    }
                    break;
                case 14:
                    // 客户买顺子
                    if (gok.isShunzi()) {
                        order.setIs_win(1);
                    }
                    break;
                case 15:
                    // 客户买三条
                    if (gok.isSan()) {
                        order.setIs_win(1);
                    }
                    break;
            }
            // 如果这笔订单是英雄场
            if (order.getCapital() <= 10) {
                if (gok.getHeroId() == 0) {
                    order.setIs_win(2);
                } else {
                    if (order.getCapital() == gok.getHeroId()) {
                        // 中奖
                        order.setIs_win(1);
                    }
                }
            }


            if (order.getIs_win() != 0) {
                Juejinuser juejinuser = getJueUserById(order.getUserid().toString());
                if (juejinuser == null) {
                    log.info("用户" + order.getUserid().toString() + "为空");
                    return;
                }
                if (order.getIs_win() == 1) {
                    //客户赢了 ，加钱
                    juejinuser.setCoin(juejinuser.getCoin() + order.getGet_amount());
                    juejinuser.setMoney(juejinuser.getMoney() + order.getGet_amount() / juejinuser.getRatio());
                    // 赢了之后获得一个宝箱
                    if (juejinuser.getStar() < 5) {
                        juejinuser.setStar(juejinuser.getStar());
                    }
                } else if (order.getIs_win() == 2) {
                    // 平局
                    juejinuser.setCoin(juejinuser.getCoin() + order.getAmount());
                    juejinuser.setMoney(juejinuser.getMoney() + order.getAmount() / juejinuser.getRatio());
                }

                // 增加英雄卡的进度
                if (juejinuser.getKnastar() != null) {
                    juejinuser.setKnastar(juejinuser.getKnastar() + 1);
                }

                // 增加3张奖券
                if (juejinuser.getTicket() != null) {
                    juejinuser.setTicket(3 + juejinuser.getTicket());
                }

                baseService.update(juejinuser);
            }


            order.setIssue(issue);
            order.setType(1);
            baseService.update(order);


        }
    }


    /**
     * 英雄的列表
     *
     * @return
     */
    @Override
    public List<Heroset> getList() {
        List<Heroset> herosetList = new ArrayList<Heroset>();

        StringBuilder selectSql0 = new StringBuilder();

        selectSql0.append(" From Heroset u where type = 1");
        herosetList = baseService.listQuery(selectSql0.toString(), Heroset.class);
        return herosetList;
    }

    /**
     * 王者荣耀在线人数的配置列表
     *
     * @return
     */
    public List<Heroset> getList2() {
        List<Heroset> herosetList = new ArrayList<Heroset>();

        StringBuilder selectSql0 = new StringBuilder();
        selectSql0.append(" From Heroset u where type = 2");
        herosetList = baseService.listQuery(selectSql0.toString(), Heroset.class);
        return herosetList;
    }

    /**
     * 名字和id的对应
     *
     * @return
     */
    @Override
    public List<Object[]> getList3() {
        List<Object[]> allList = new ArrayList<Object[]>();

        StringBuilder selectSql0 = new StringBuilder();
        selectSql0.append("select name From Heroset u where 1=1");
//        allList = dbService.getHeroList( selectSql0.toString() );
        allList = baseService.nativeQuery("select id,name,odds from sp_hero_set");
        return allList;
    }

    /**
     * 概率
     *
     * @return
     */
    public Map<String, Double> probaSet(String type) {
        Map<String, Double> mapresult = new HashMap<String, Double>();
        Heroset heroset = new Heroset();
        List l0 = new ArrayList();
        if ("hero".equals(type)) {
            l0 = getList();
            Iterator it = getList().iterator();
            while (it.hasNext()) {
                heroset = (Heroset) it.next();
                mapresult.put(heroset.getId().toString(), heroset.getPercent());
            }
        } else if ("digit".equals(type)) {
            l0 = getList2();
            Iterator it = l0.iterator();
            while (it.hasNext()) {
                Heroset digitse = (Heroset) it.next();
                mapresult.put(digitse.getId().toString(), digitse.getPercent());
            }
        }


        return mapresult;
    }

    @Override
    public String getAccesstoken(String appid) {
        StringBuilder hql = new StringBuilder();
        hql.append("From Wxuser where wxid = '");
        hql.append(appid);
        hql.append("'");
        List<Wxuser> wxusers = baseService.listQuery(hql.toString(), Wxuser.class);
        Wxuser wxuser = wxusers.get(0);
        return wxuser.getAccessToken();
    }


    /**
     * 赔率
     *
     * @return
     */
    @Override
    public Map<Integer, Double> oddsSet(String type) {
        Map<Integer, Double> mapresult = new HashMap<Integer, Double>();
        List l0 = new ArrayList();
        if ("hero".equals(type)) {
            l0 = getList();
            Iterator it = l0.iterator();
            while (it.hasNext()) {
                Heroset heroset = (Heroset) it.next();
                mapresult.put(heroset.getId().intValue(), heroset.getOdds());
            }
        } else if ("digit".equals(type)) {
            l0 = getList2();
            Iterator it = l0.iterator();
            while (it.hasNext()) {
                Heroset heroset = (Heroset) it.next();
                mapresult.put(heroset.getId().intValue(), heroset.getOdds());
            }
        }
        return mapresult;
    }


    @Override
    public Wxuser getWx(String token) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From Wxuser where token ='");
        stringBuilder.append(token);
        stringBuilder.append("'");

        Wxuser wxuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Wxuser.class);
        return wxuser;
    }

    @Override
    public Wxuser getWxByWxid(String weixinId) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From Wxuser where wxid ='");
        stringBuilder.append(weixinId);
        stringBuilder.append("'");

        Wxuser wxuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Wxuser.class);
        return wxuser;
    }

    /**
     * @return
     */
    @Override
    public UsernameToken getUser() {
        // 获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernameToken token = new UsernameToken();


        PrincipalCollection pr = subject.getPrincipals();
        if (pr != null) {
            Object o1 = pr.getPrimaryPrincipal();
            token = (UsernameToken) subject.getPrincipals().getPrimaryPrincipal();
            return token;
        } else {
            return null;
        }
    }

    @Override
    public WxConfig getWxPayConfig(String plat) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From WxConfig where name ='");
        stringBuilder.append(plat);
        stringBuilder.append("'");

        WxConfig wxConfig = baseService.queryObjectFromMaster(stringBuilder.toString(), WxConfig.class);
        return wxConfig;

    }

    @Override
    public String getWxPaySecret(String mchtId) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From WxConfig where mchId ='");
        stringBuilder.append(mchtId);
        stringBuilder.append("'");

        WxConfig wxConfig = baseService.queryObjectFromMaster(stringBuilder.toString(), WxConfig.class);

        return wxConfig.getApiSecret();
    }

    @Override
    public boolean addMoney(double money, String ordersn) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From PayOrder where status != 2 and ordersn ='");
        stringBuilder.append(ordersn);
        stringBuilder.append("'");

        PayOrder payOrder = baseService.queryObjectFromMaster(stringBuilder.toString(), PayOrder.class);

        if (payOrder != null) {
            payOrder.setStatus(2);// 设置成功

            baseService.update(payOrder);// 更新订单

            stringBuilder.setLength(0);
            stringBuilder.append("From Juejinuser where id = ");
            stringBuilder.append(payOrder.getUserid());
            Juejinuser juejinuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Juejinuser.class);
            log.info("用户" + juejinuser.getId() + "原来的金额是" + juejinuser.getMoney());
            double newmoney = juejinuser.getMoney() + money;
            double newCoin = juejinuser.getCoin() + money * juejinuser.getRatio();
            juejinuser.setMoney(newmoney);
            juejinuser.setCoin(newCoin);
            if (juejinuser.getAddmoney() != null) {
                juejinuser.setAddmoney(juejinuser.getAddmoney() + newmoney);
            } else {
                juejinuser.setAddmoney(newmoney);
            }

            baseService.update(juejinuser);// 更新用户记录
        }

        DatabaseContextHolder.setCustomerType("dataSource");
        try {
            Qwuser qwuser = baseService.queryObject("From Qwuser where user_id = 1", Qwuser.class);
            if (qwuser.getBook_money() != null) {
                qwuser.setBook_money((int) (qwuser.getBook_money() + money));
            }

        } finally {
            DatabaseContextHolder.clearCustomerType();
        }
        return true;
    }

    @Override
    public boolean vipMoney(double money, String ordersn) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From PayOrder where ordersn ='");
        stringBuilder.append(ordersn);
        stringBuilder.append("'");
        PayOrder payOrder = baseService.queryObjectFromMaster(stringBuilder.toString(), PayOrder.class);

        stringBuilder.setLength(0);
        stringBuilder.append("From Juejinuser where id = ");
        stringBuilder.append(payOrder.getUserid());
        Juejinuser juejinuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Juejinuser.class);


        int mo = (int) money;
        switch (mo) {
            case 30:
                juejinuser.setCoin(juejinuser.getCoin() + 50);
                juejinuser.setTicket(juejinuser.getTicket() + 20);
                break;
            case 90:
                juejinuser.setCoin(juejinuser.getCoin() + 150);
                juejinuser.setTicket(juejinuser.getTicket() + 60);
                break;
            case 200:
                juejinuser.setCoin(juejinuser.getCoin() + 600);
                juejinuser.setTicket(juejinuser.getTicket() + 150);
                break;
            case 300:
                juejinuser.setCoin(juejinuser.getCoin() + 1000);
                juejinuser.setTicket(juejinuser.getTicket() + 300);
                break;
            case 500:
                juejinuser.setCoin(juejinuser.getCoin() + 1500);
                juejinuser.setTicket(juejinuser.getTicket() + 600);
                break;
        }

        baseService.update(juejinuser);


        return false;
    }

    @Override
    public boolean addMoneyfail(String ordersn) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From PayOrder where ordersn ='");
        stringBuilder.append(ordersn);
        stringBuilder.append("'");

        PayOrder payOrder = baseService.queryObjectFromMaster(stringBuilder.toString(), PayOrder.class);
        payOrder.setStatus(3);
        baseService.update(payOrder);
        return true;
    }

    @Override
    public boolean updateTiOrder(TiOrder tiOrder) {
//        // 同时减少juejin_users表里的金额
//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("From Juejinuser where id = ");
//        stringBuilder.append(tiOrder.getUserid());
//
//        Juejinuser juejinuser = baseService.singleQueryFromMaster( stringBuilder.toString(), Juejinuser.class );
//
//
//        // 确认账户上有足够的余额进行提现
//        if( juejinuser.getMoney() < tiOrder.getPrice() ){
//            return false;
//        }
//
//        juejinuser.setCoin( juejinuser.getCoin() -  tiOrder.getPtmoney()*juejinuser.getRatio() );
//        juejinuser.setMoney( juejinuser.getMoney() - tiOrder.getPtmoney() );
//        juejinuser.setBuffer_money( juejinuser.getBuffer_money() + tiOrder.getPtmoney() );
//        baseService.update( juejinuser );

        baseService.update(tiOrder);

        return true;
    }

    @Override
    public boolean cashsuccess(double ptmoney, String ordersn) {

        // 提现成功
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From TiOrder where status != 2 and ordersn = '");
        stringBuilder.append(ordersn);
        stringBuilder.append("'");

        List<TiOrder> list = baseService.listQuery(stringBuilder.toString(), TiOrder.class);
        if (list.size() > 1 || list.size() == 0) {
            return false;
        }

        TiOrder tiOrder = list.get(0);
        tiOrder.setStatus(2);// 提现成功

        GiftExchange giftExchange = getGiftById(tiOrder.getGiftid());
        giftExchange.setStatus(2);// 退货成功
        baseService.update(giftExchange);

        baseService.update(tiOrder);


        stringBuilder.setLength(0);
        stringBuilder.append("From Juejinuser where id = ");
        stringBuilder.append(tiOrder.getUserid());
        Juejinuser juejinuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Juejinuser.class);

//        juejinuser.setBuffer_money( juejinuser.getBuffer_money() - ptmoney );
//        baseService.update( juejinuser );

        return true;
    }

    @Override
    public boolean cashfail(String ordersn, String remark) {

        // 提现失败
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From TiOrder where ordersn = '");
        stringBuilder.append(ordersn);
        stringBuilder.append("'");

        List<TiOrder> list = baseService.listQuery(stringBuilder.toString(), TiOrder.class);
        if (list.size() > 1 || list.size() == 0) {
            return false;
        }

        TiOrder tiOrder = list.get(0);
        tiOrder.setStatus(3);
        tiOrder.setRemark(remark);

        baseService.update(tiOrder);


        stringBuilder.setLength(0);
        stringBuilder.append("From Juejinuser where id = ");
        stringBuilder.append(tiOrder.getUserid());
        Juejinuser juejinuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Juejinuser.class);

//        juejinuser.setBuffer_money( juejinuser.getBuffer_money() - tiOrder.getPtmoney() );
        juejinuser.setMoney(juejinuser.getMoney() + tiOrder.getPrice());
        baseService.update(juejinuser);


        return false;
    }

    /**
     * 获取2小时之前到2分钟之前到未获得准确返回结果的充值订单
     *
     * @param plat
     * @return
     */
    @Override
    public List<PayOrder> getPayList(String plat) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From PayOrder where status = 0 and createtime between");
        stringBuilder.append((System.currentTimeMillis() / 1000 - 3600 * 2));
        stringBuilder.append(" and ");
        stringBuilder.append((System.currentTimeMillis() / 1000 - 60 * 2));
//        stringBuilder.append("From PayOrder where status = 0");

        List<PayOrder> payOrders = baseService.listQuery(stringBuilder.toString(), PayOrder.class);

        return payOrders;
    }

    @Override
    public List<TiOrder> getTiList(String plat) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From TiOrder where status = 0 and createtime between");
        stringBuilder.append((System.currentTimeMillis() / 1000 - 3600 * 2));
        stringBuilder.append(" and ");
        stringBuilder.append((System.currentTimeMillis() / 1000 - 60 * 2));
//        stringBuilder.append("From TiOrder where status = 0");

        List<TiOrder> tiOrders = baseService.listQuery(stringBuilder.toString(), TiOrder.class);

        return tiOrders;
    }

    /**
     * 玩家个人的充值记录
     *
     * @param userid
     * @param page
     * @return
     */
    @Override
    public List<PayOrder> getPayList(String userid, String page) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From PayOrder where userid = ");
        stringBuilder.append(userid);
        stringBuilder.append("order by createtime desc");

        QueryHelper queryHelper = new QueryHelper();

        int start = (Integer.parseInt(page) - 1) * 20;
        int end = Integer.parseInt(page) * 20;

        queryHelper.setOffset(start);
        queryHelper.setLimit(end);
        List<PayOrder> payOrderList = baseService.listQueryForPage(stringBuilder.toString(), PayOrder.class, queryHelper);
        return payOrderList;
    }

    @Override
    public List<TiOrder> getTiList(String userid, String page) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From TiOrder where userid = ");
        stringBuilder.append(userid);
        stringBuilder.append("order by createtime desc");

        QueryHelper queryHelper = new QueryHelper();

        int start = (Integer.parseInt(page) - 1) * 20;
        int end = Integer.parseInt(page) * 20;

        queryHelper.setOffset(start);
        queryHelper.setLimit(end);
        List<TiOrder> tiOrderList = baseService.listQueryForPage(stringBuilder.toString(), TiOrder.class, queryHelper);
        return tiOrderList;
    }

    /*
    获取该用户所有的礼物
     */
    @Override
    public List<GiftExchange> getGiftlist(String userid, String page) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From GiftExchange where userid = ");
        stringBuilder.append(userid);
        stringBuilder.append("order by createtime desc");

        QueryHelper queryHelper = new QueryHelper();

        int start = (Integer.parseInt(page) - 1) * 20;
        int end = Integer.parseInt(page) * 20;

        queryHelper.setOffset(start);
        queryHelper.setLimit(end);
        List<GiftExchange> tiOrderList = baseService.listQueryForPage(stringBuilder.toString(), GiftExchange.class, queryHelper);
        return tiOrderList;

    }

    @Override
    public boolean addCount(Count count) {
        try {
            baseService.update(count);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 增加兑换礼品的记录
     *
     * @param giftExchange
     */
    @Override
    public String addExchangeOrder(GiftExchange giftExchange) {
        baseService.update(giftExchange);
        // 用户表减金额
        Juejinuser juejinuser = getJueUserById(giftExchange.getUserid().toString());
        // 先判断用户的余额是否足够
        if (juejinuser.getCoin() < giftExchange.getMoney()) {
            return "coin not enough";
        }

        juejinuser.setCoin(juejinuser.getCoin() - giftExchange.getMoney());
//        juejinuser.setBuffer_money( juejinuser.getBuffer_money() + giftExchange.getMoney()/juejinuser.getRatio() );

        juejinuser.setMoney(juejinuser.getMoney() - (giftExchange.getMoney() / juejinuser.getRatio()));

        baseService.update(juejinuser);
        return "";
    }


    @Override
    public GiftExchange getGiftById(Integer id) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From GiftExchange where id = ");
        stringBuilder.append(id);
        GiftExchange giftExchange = baseService.queryObjectFromMaster(stringBuilder.toString(), GiftExchange.class);
        return giftExchange;
    }

    /**
     * 给客户增加英雄卡
     *
     * @param userid
     * @return
     */
    @Override
    public JSONObject getKnapsackWinHero(Long userid) {
        JSONObject result = new JSONObject();
        Juejinuser juejinuser = getJueUserById(userid.toString());
        // 判断有没有到第三次下单
        Heroset heroset = baseService.queryObject("From Heroset where type = 4", Heroset.class);
        int shouldCount = 0;
        if (heroset != null) {
            shouldCount = (int) (heroset.getOdds() * 1d);
        }
        if (shouldCount == 0) {
            return result;
        }
        if (shouldCount != juejinuser.getKnastar()) {
            return result;
        }

        int herowin = 999;
        List<KnaspPro> knaspPros = baseService.listQuery("From KnaspPro", KnaspPro.class);
        int num = (int) (Math.random() * 10000);

        // 生成新的数组用来计算
        double[] knaspros2;
        knaspros2 = new double[10];
        knaspros2[0] = 0;

        for (int i = 1; i < 10; i++) {
            double sum = 0;
            for (int j = 0; j < i; j++) {
                sum += knaspPros.get(j).getProbability() * 100;
            }
            knaspros2[i] = sum;
        }

        for (int i = 0; i < 9; i++) {
            if (num > knaspros2[i] && num <= knaspros2[i + 1]) {
                // 中奖了
                result.put("winhero", knaspPros.get(i).getHeroId());
                herowin = knaspPros.get(i).getHeroId();
            } else {
                log.info("中奖范围" + knaspros2[i] + "到" + knaspros2[i + 1] + "。实际数字是" + num);
            }
        }

        if (herowin != 999) {
            // 给用户增加英雄卡
            juejinuser = getJueUserById(userid.toString());
            // getHeroId从1开始
            String kna = juejinuser.getKnapsack();
            String[] ss1 = kna.split(",");

            String s1 = (Integer.parseInt(ss1[herowin]) + 1) + "";
            ss1[herowin] = s1;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 9; i++) {
                stringBuilder.append(ss1[i]);
                stringBuilder.append(",");
            }
            String s2 = stringBuilder.toString();
            String s3 = s2.substring(0, s2.length() - 1);
            juejinuser.setKnapsack(s3);
            juejinuser.setKnastar(0);
            updateUser(juejinuser);
        }
        return result;
    }

    @Override
    public String getPasswdByPhone(String phone) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From Juejinuser where phone = '");
        stringBuilder.append(phone);
        stringBuilder.append("'");

        Juejinuser juejinuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Juejinuser.class);
        if (juejinuser != null) {
            return juejinuser.getPassword();
        }
        return "";
    }

    /**
     * 根据token获取会员
     *
     * @param token
     * @return
     */
    @Override
    public Users getMemberByToken(String token) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From Wxuser where token = '");
        stringBuilder.append(token);
        stringBuilder.append("'");
        Wxuser wxuser = baseService.queryObjectFromMaster(stringBuilder.toString(), Wxuser.class);
        if (wxuser == null) {
            return null;
        }
        stringBuilder.setLength(0);

        stringBuilder.append("From Users where gid = 2 and id =");
        stringBuilder.append(wxuser.getUid());
        Users users = baseService.queryObjectFromMaster(stringBuilder.toString(), Users.class);
        return users;
    }

    /**
     * 根据id获得sp_users表里的内容
     *
     * @param id
     * @return
     */
    @Override
    public Users getAdUsersById(Integer id) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From Users where id = ");
        stringBuilder.append(id);
        Users users1 = baseService.queryObjectFromMaster(stringBuilder.toString(), Users.class);
        return users1;
    }

    /**
     * 根据客户的token，计算出会员单位和运营中心应该获得的手续费
     *
     * @param token
     */
    @Override
    public void calcFeeForUser(String token, double ordermoney) {
        Users users1 = getMemberByToken(token);// 会员单位
        if (users1 == null) {
            return;
        }
        double d1 = users1.getFeemoney() + ordermoney * 0.1 * 0.85;
        users1.setFeemoney(d1);
        baseService.update(users1);


        Users users2 = getAdUsersById(users1.getPid());// 运营中心
        if (users2 == null) {
            return;
        }
        d1 = users2.getFeemoney() + ordermoney * 0.1 * 0.05;
        users2.setFeemoney(d1);
        baseService.update(users2);

        // 总平台的手续费
        Users users3 = getAdUsersById(1);// 运营中心
        if (users3 == null) {
            return;
        }
        d1 = users3.getFeemoney() + ordermoney * 0.1 * 0.1;
        users3.setFeemoney(d1);
        baseService.update(users3);

    }

    public Chestlist getChestById(Integer id) {
        Chestlist chestlist = baseService.queryObjectFromMaster("From Chestlist where id = " + id, Chestlist.class);
        return chestlist;
    }


    // 更换宝箱。38个宝箱
    @Override
    public boolean exchangeTicket(Juejinuser juejinuser, Integer chestId) {
        if (chestId.equals((juejinuser.getChestId() + 1))) {


            juejinuser.setChestId(chestId);
            Chestlist chestlist = getChestById(chestId);


            if (juejinuser.getTicket() < chestlist.getTicket()) {
                return false;
            }

            juejinuser.setCoin(juejinuser.getCoin() + chestlist.getCoin() * 1d);
            juejinuser.setMoney(chestlist.getCoin() * juejinuser.getRatio() + juejinuser.getMoney());
            juejinuser.setTicket(juejinuser.getTicket() - chestlist.getTicket());
            updateUser(juejinuser);
            return true;
        } else {
            return false;
        }


    }

    //接受英雄卡，
    @Override
    public boolean KnapsackCardAdd(Juejinuser juejinuser, Integer herowin, String idFrom) {
        if (idFrom.equals("")) {
            log.info("idFrom为空");
            return false;
        }


        Juejinuser userFrom = getJueUserById(idFrom);

        if (userFrom == null) {
            log.info("userFrom为空");
            return false;
        }


        String kna = juejinuser.getKnapsack();// 所有英雄卡数字的字符串
        String[] ss1 = kna.split(",");
        String s1 = (Integer.parseInt(ss1[herowin] + 1)) + "";// 增加英雄卡之后，该张英雄卡的拥有数字
        ss1[herowin] = s1;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 9; i++) {
            stringBuilder.append(ss1[i]);
            stringBuilder.append(",");
        }
        String s2 = stringBuilder.toString();
        String s3 = s2.substring(0, s2.length() - 1);
        log.info("接收之后拼接出来的英雄卡数组"+s3);
        juejinuser.setKnapsack(s3);

        juejinuser.setKnapsack(s3);
        updateUser(juejinuser);// 接收英雄卡成功

        return true;
    }

    // 减少英雄卡
    @Override
    public String KnapsackCardDelete(Juejinuser juejinuser, Integer herowin) {

        String s1 = juejinuser.getKnapsack();
        String ss1[] = s1.split(",");

        String s2 = ss1[herowin];
        Integer s3 = Integer.parseInt(s2);
        if (s3 > 0) {
            s3--;
        } else {
            return "nocards";
        }

        ss1[herowin] = s3 + "";
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 9; i++) {
            stringBuilder.append(ss1[i]);
            stringBuilder.append(",");
        }

        s2 = stringBuilder.toString();
        String s4 = s2.substring(0, s2.length() - 1);
        log.info("赠送之后用户拥有的卡片" + s1);
        juejinuser.setKnapsack(s4);
        updateUser(juejinuser);
        return "success";
    }

    /**
     * 验证签名是否正确，正确给该用户增加一张英雄卡
     *
     * @param ciph
     * @param type
     */
    @Override
    public boolean cardAdd(String ciph, String type, Juejinuser juejinuser) {
        String express = "type=" + type + "&userid=" + juejinuser.getId() + "JLSfWRRoCt5idlsB";
        log.info("加密字符串" + express);
        String ciphertext = Funutil.encode(express);
        if (!ciphertext.equals(ciph)) {
            log.info("用户" + juejinuser.getId() + "签名错误");
            return false;
        }
        // 签名验证通过
        KnapsackCardAdd(juejinuser, Integer.parseInt(type), "");
        return true;
    }

    /**
     * 获得已赠送但未接收的英雄卡片
     *
     * @param UseId
     * @param type
     * @return
     */
    @Override
    public KnapgiftRecord getKnaByUserType(String UseId, String type) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From KnapgiftRecord where userIdFrom = ");
        stringBuilder.append(UseId);
        stringBuilder.append(" and type= ");
        stringBuilder.append(type);
        stringBuilder.append(" and status = 0 order by createtime");

        log.info(stringBuilder.toString());



        // final String hql, Class<T> modelClass, QueryHelper queryHelper);
        List<KnapgiftRecord> knapgiftRecords = baseService.listQuery(stringBuilder.toString(), KnapgiftRecord.class );
        if (knapgiftRecords.size() == 0) {
            return null;
        }
        KnapgiftRecord knapgiftRecord = knapgiftRecords.get(0);

        return knapgiftRecord;
    }


}
